package com.itheima.huikebackend.interceptor;


import com.alibaba.fastjson.JSON;
import com.itheima.huikebackend.common.R;
import com.itheima.huikebackend.context.BaseContext;
import com.itheima.huikebackend.enums.HttpStatusCodeEnum;
import com.itheima.huikebackend.enums.LoginProEnum;
import com.itheima.huikebackend.properties.JwtProperties;
import com.itheima.huikebackend.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;


@Slf4j
@Component
@RequiredArgsConstructor
public class LoginHandlerInterceptor implements HandlerInterceptor {

    private final JwtProperties jwtProperties;

    private final JwtUtil jwtUtil;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        Cookie[] cookies = request.getCookies();
        String token = getCookie(cookies, jwtProperties.getHeader());
        if (!StringUtils.hasLength(token)) {
           return err(response);
        }
        try {
            Claims claims = jwtUtil.parseJWT(token);
            Long id = claims.get(LoginProEnum.USER_ID.value, Long.class);
            String  userName = claims.get("userName", String.class);
            Long  deptId = claims.get("deptId", Long.class);
            Map map = new HashMap();
            map.put("id",String.valueOf(id));
            map.put("userName",userName);
            map.put("deptId",String.valueOf(deptId));
            BaseContext.setCurrentInfo(map);
            return true;
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return err(response);
        }
    }

    /**
     * 异常情况
     *
     * @param response 响应
     * @return boolean
     * @throws IOException ioexception
     */
    private static boolean err(HttpServletResponse response) throws IOException {
        R<?> error = R.error(HttpStatusCodeEnum.UNAUTHORIZED.code, "出错了");
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json");
        response.getWriter().write(JSON.toJSONString(error));
        return false;
    }

    /**
     * 获取cookie值
     * @param cookies
     * @param target
     * @return
     */
    private static String getCookie(Cookie[] cookies, String target) {
        if(cookies != null){
            for(Cookie cookie : cookies){
                if(cookie.getName().equals(target)){
                    return cookie.getValue();
                }
            }
        }
        return null;
    }
}
